import { CourseItem } from '@/pages/pc/components/Course';
import { Select, Skeleton } from 'antd';
import Pagination from '@/pages/pc/components/Pagination';
import styles from './index.less';
import { useState, useEffect } from 'react';
import CheckTag from '@/pages/pc/components/CheckTag';
import classNames from 'classnames';
import qs from 'qs';
import VideoPlayerModal from '../components/VideoPlayer';
import { allGet } from '@/services/pc';
import { Link, useHistory, Helmet } from 'umi';
import Empty from '../components/Empty';

const order = [
  { label: '最新', value: '-9999' },
  /*   { label: '最新', value: '2' }, */
  { label: '热销', value: '3' },
  { label: '价格', value: ['4', '5'] },
  { label: '免费', value: '1' },
];

const pageSize = 24;
const Index = (props) => {
  // useEffect(() => {
  //     VideoPlayerModal.showScore({
  //         data: [
  //           { url: 'https://cgjoy.oss-cn-shanghai.aliyuncs.com/train/202106/1624348940/杨超_水弹.mp4' },
  //           {
  //             url: 'https://cgjoy.oss-cn-shanghai.aliyuncs.com/train/202106/1624349356/%E5%91%A8%E5%B2%9A%E6%9E%97_%E7%80%91%E5%B8%83.mp4'
  //           },
  //           {
  //             url: 'https://cgjoy.oss-cn-shanghai.aliyuncs.com/train/202106/1624349232/周岚林_菲尼爾.mp4'
  //           }
  //         ]
  //       });
  // }, [])

  const { query = {}, search, match } = props;
  const history = useHistory();
  const [loading, setLoading] = useState(true);
  const handleChangeSearch = (key, value, others = {} as any) => {
    console.log(key, value, '2323232');
    if (loading) return;
    setLoading(true);
    const newQuery = query;
    if (Array.isArray(value)) {
      newQuery[key] = value?.[0];
    } else {
      newQuery[key] = value;
    }
    // if (key === 'order') {
    //   if (value[0] === '4') {
    //     newQuery.order = 'price';
    //     newQuery.descasc = 'asc';
    //   } else if (value[0] === '5') {
    //     newQuery.order = 'price';
    //     newQuery.descasc = 'desc';
    //   } else {
    //     newQuery[key] = value?.[0];
    //   }
    // } else {
    //   if (Array.isArray(value)) {
    //     newQuery[key] = value?.[0];
    //   } else {
    //     newQuery[key] = value;
    //   }
    // }

    // if (newQuery?.order === 'price') {
    //   if (!others?.descasc) {
    //     newQuery.descasc = 'desc';
    //   } else {
    //     newQuery.descasc = others.descasc;
    //   }
    // } else {
    //   newQuery.descasc = '';
    // }
    // if (key === 'price' && value === '-1') {
    //   newQuery.descasc = '';
    //   newQuery.order = '';
    // } else {
    //   newQuery.price = '';
    // }
    console.log(newQuery, query);
    const string = qs.stringify(query);
    history.push(`/courses/${1}?${string}`);
  };

  const itemRender = (current, type, originalElement) => {
    if (type === 'page') {
      return (
        <Link to={`/courses/${current}${search}`} onClick={() => setLoading(true)}>
          {current}
        </Link>
      );
    }
    if (type === 'next') {
      return (
        <Link to={`/courses/${current}${search}`} onClick={() => setLoading(true)}>
          {originalElement}
        </Link>
      );
    }
    if (type === 'prev') {
      return (
        <Link to={`/courses/${current}${search}`} onClick={() => setLoading(true)}>
          {originalElement}
        </Link>
      );
    }

    return originalElement;
  };

  // 分类
  const [column, setColumn] = useState<any>([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({
        params: { mod: 'course', do: 'category', version: 'pc1.0' },
      });
      const arr: any[] =
        response?.data?.map((item) => ({ label: item.name, value: item.cid })) || [];
      arr.unshift({ label: '全部', value: '-9999' });
      setColumn(arr);
    })();
  }, []);

  // 软件
  const [software, setSoftware] = useState<any>([]);
  useEffect(() => {
    (async () => {
      const response = await allGet({ params: { mod: 'course', do: 'soft', version: 'pc1.0' } });
      const arr: any[] =
        response?.data?.list?.map((item) => ({ label: item.subject, value: item.sid })) || [];
      arr.unshift({ label: '全部', value: '-9999' });
      setSoftware(arr);
    })();
  }, []);
  useEffect(() => {
    if (props.initialPropsOk === true) {
      setLoading(false);
    }
  }, [props.initialPropsOkTime, props.initialPropsOk]);
  return (
    <div className={styles.page}>
      <Helmet>
        <title>全部课程 - CGJOY课堂</title>
        <meta name="title" content="全部课程 - CGJOY课堂" />
        <meta name="keywords" content={props.keywords} />
        <meta name="description" content={props.description} />
      </Helmet>
      <div className={styles.header}>
        <div className={styles.row}>
          <div className={styles.key}>分类：</div>
          <CheckTag
            controled
            data={column}
            defaultValue={[query.cid || '']}
            onChange={(value) => handleChangeSearch('cid', value)}
          />
        </div>
        <div className={styles.row}>
          <div className={styles.key}>软件：</div>
          <CheckTag
            controled
            data={software}
            defaultValue={[query.sid || '']}
            onChange={(value) => handleChangeSearch('sid', value)}
          />
        </div>
        <div className={styles.row}>
          <div className={styles.key}>排序：</div>
          <CheckTag
            controled
            data={order}
            defaultValue={[query.order || '']}
            onChange={(value) => handleChangeSearch('order', value)}
          />
        </div>
      </div>
      {/* <div className={styles.header}>
        <div className={styles.left}>
          <div className={styles.fieds}>
            <span className={styles.key}>分类：</span>
            <Select
              placeholder="游戏特效"
              className={styles.select}
              onChange={(value) => handleChangeSearch('cid', value)}
              value={column?.length > 0 ? query?.cid : undefined}
            >
              {column?.map((item) => {
                return (
                  <Select.Option key={item.value} value={item.value}>
                    {item.label}
                  </Select.Option>
                );
              })}
            </Select>
          </div>
          <div className={styles.fieds}>
            <span className={styles.key}>软件：</span>
            <Select
              placeholder="软件"
              className={styles.select}
              onChange={(value) => handleChangeSearch('sid', value)}
              value={software?.length > 0 ? query?.sid : undefined}
            >
              {software?.map((item) => {
                return (
                  <Select.Option key={item.value} value={item.value}>
                    {item.label}
                  </Select.Option>
                );
              })}
            </Select>
          </div>
        </div>
        <div className={styles.order}>
          <span
            className={classNames(styles.item, { [styles.active]: query?.price == '-1' })}
            onClick={() => handleChangeSearch('price', '-1')}
          >
            免费
          </span>
          <span
            className={classNames(styles.item, { [styles.active]: query?.order == 'classid' })}
            onClick={() => handleChangeSearch('order', 'classid')}
          >
            最新
          </span>
          <span
            className={classNames(styles.item, { [styles.active]: query?.order == 'lastsale' })}
            onClick={() => handleChangeSearch('order', 'lastsale')}
          >
            热销
          </span>
          <span
            className={classNames(styles.item, { [styles.active]: query?.order == 'price' })}
            onClick={() =>
              handleChangeSearch('order', 'price', {
                descasc: query?.descasc === 'desc' ? 'asc' : 'desc',
              })
            }
          >
            价格
            <div className={styles.icons}>
              <i className={classNames(styles.up, { [styles.active]: query?.descasc === 'asc' })} />
              <i
                className={classNames(styles.down, { [styles.active]: query?.descasc === 'desc' })}
              />
            </div>
          </span>
        </div>
      </div> */}
      <div className={styles.main}>
        <div className={styles.list}>
          {loading === true ? (
            <div
              style={{
                display: 'grid',
                width: '100%',
                gridTemplateColumns: '1fr 1fr 1fr 1fr',
                gap: 20,
              }}
            >
              {new Array(20).fill(1).map((num, index) => (
                <Skeleton key={index + num} active />
              ))}
            </div>
          ) : props?.course?.data?.list?.length > 0 ? (
            props?.course?.data?.list?.map((item) => (
              // eslint-disable-next-line react/jsx-key
              <div className={styles.item}>
                <CourseItem id={item.classid} {...item} open />
              </div>
            ))
          ) : (
            <Empty />
          )}
        </div>
      </div>
      {props?.course?.data?.count > pageSize && (
        <Pagination
          pageSize={pageSize}
          itemRender={itemRender}
          className={styles.pagination}
          total={props?.course?.data?.count}
          current={parseInt(match?.params?.page)}
        />
      )}
    </div>
  );
};

function getRandomElementsByIndices(array, count) {
  if (array.length < count) {
    throw new Error('数组长度不足');
  }

  const indices = [];
  const result = [];
  const usedIndices = new Set();

  while (indices.length < count) {
    const randomIndex = Math.floor(Math.random() * array.length);
    if (!usedIndices.has(randomIndex)) {
      indices.push(randomIndex);
      usedIndices.add(randomIndex);
      result.push(array[randomIndex]);
    }
  }

  return result;
}

export default Index;

Index.getInitialProps = async ({ match, history, isServer }) => {
  console.log(isServer, 2222);
  const { query, search } = history?.location || {};
  const params: any = {
    mod: 'course',
    do: 'list',
    // oride: 'classid',
    perpage: pageSize,
    page: match?.params?.page,
    version: 'pc1.0',
  };
  if (query.cid && query.cid !== '-9999') {
    params.cid = query.cid;
  }
  if (query.sid && query.sid !== '-9999') {
    params.sid = query.sid;
  }
  if (query.order) {
    if (query.order === '4') {
      params.order = 'price';
      params.descasc = 'asc';
    } else if (query.order === '5') {
      params.order = 'price';
      params.descasc = 'desc';
    } else if (query.order === '3') {
      params.order = 'lastsale';
    } else if (query.order === '2') {
      params.order = 'classid';
    } else if (query.order === '1') {
      params.price = '-1';
    }
  }
  if (query.keyword) {
    params.kw = query.keyword;
  }
  // if (query.descasc) {
  //   params.descasc = query.descasc;
  // }
  // if (query.price) {
  //   params.price = query.price;
  // }
  const [course, columnResponse, softwareResponse] = await Promise.all([
    allGet({ params }),
    allGet({
      params: { mod: 'course', do: 'category', version: 'pc1.0' },
    }),
    allGet({
      params: { mod: 'course', do: 'soft', version: 'pc1.0' },
    }),
  ]);
  const keywords = [
    ...(columnResponse.data?.map?.((item) => item.name) || []),
    ...softwareResponse.data?.list?.map?.((item) => item.subject),
  ].join(',');
  const description = (course?.data?.list?.map?.((item) => item.name) || [])
    .join(',')
    .slice(0, 100);
  /*   if (course?.data?.list.length > 18 && Array.isArray(course.data.list)) {
    const randomElements = getRandomElementsByIndices(
      course.data.list,
      24 - course.data.list.length,
    );
    course.data.list = [...course.data.list, ...randomElements];
  } */
  return {
    initialPropsOk: true,
    initialPropsOkTime: Date.now(),
    course,
    match,
    query,
    search,
    isServer,
    keywords,
    description,
  };
};
